package com.tianji.promotion.utils;


import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class UserCouponLockAspect implements Ordered {
    private final LockFactory lockFactory;
    @Around("@annotation(userCouponLock)")
    public Object tryLock(ProceedingJoinPoint pjp, UserCouponLock userCouponLock) throws Throwable {
        //1、创建锁对象
        RLock lock = lockFactory.getLock(userCouponLock.name(), userCouponLock.lockType());
        //2、尝试获取锁
        boolean isLock = userCouponLock.lockStrategy().tryLock(lock, userCouponLock);
        //3、获取锁失败，直接返回
        if (!isLock) {
           return null;
        }
        try {
            //4、获取成功，执行业务
            return pjp.proceed();
        } finally {
            //5、释放锁
            lock.unlock();
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }

}
